package com.example.mongo.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils {
    public static String getCookie(HttpServletRequest request, String cookieName) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(cookieName)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    public static void setCookie(HttpServletResponse response, String cookieName, String value) {
        Cookie cookie = new Cookie(cookieName, value);
        cookie.setPath("/");
        cookie.setMaxAge(5 * 60);
        response.addCookie(cookie);
    }

    public static String isLogin(HttpServletRequest request,RedisUtil redisUtil){
        String uuid = CookieUtils.getCookie(request,"UUID");   //cookie 中存储  UUID=【Redis key】
        if(null==uuid){             //未登录 前端无 cookie 【重新登录】
            return "false";
        }
        String id = (String) redisUtil.get(uuid);                           //从Redis中根据 cookie中存储的key 获取userid；
        if(null==id){               //cookie 过期 【重新登录】
            return "false";
        }
        return id;
    }






}
